﻿using CqCore.DB;
using SuperShopInfrastructure.Extensions;
using SuperShopInfrastructure.Models.Order;
using SuperShopRepository.Dbs;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Threading.Tasks;

namespace SuperShopRepository
{
    public class ShopCartRepository
    {
        private readonly ISqlService<SuperShopCustomerDb> sqlService;

        public ShopCartRepository(ISqlService<SuperShopCustomerDb> sqlService)
        {
            this.sqlService = sqlService;
        }

        public async Task<DataSet> GetShopCartList(string skuids)
        {
            SqlParameter[] parms =
            {
                new SqlParameter("@skuids",skuids)
            };
            var sql = "select ps.ProductId,ps.Id as Product_SkuId, p.ProductName,p.Brand,ps.StockNum,ps.SallPrice,ps.SkuType,ps.ProppetyCombineName,(select ImagePath from C_ProductImg where ProductId=ps.ProductId and IsDel=0 and IsDefault=1)as ImgPath,ps.IsDel,p.ShippingTemplateId,ps.Weight  from C_Product_Sku ps left join C_Product p on ps.ProductId = p.Id where ps.Id in(" + skuids + ")";
            return await sqlService.ExecuteDataset(CommandType.Text, sql, parms);
        }

        public async Task<bool> CreateOrderInsert(CreateOrderCommand command)
        {
            //下订单时，将商品临时插入表，这样存储过程就直接可以计算了
            var sqlList = new List<string>();
            var _userid = command.UserId.ToInt();
            sqlList.Add("update  C_ShoppingCart set IsDel=1 where UserId=" + _userid + ";");
            foreach (var item in command.CreateOrder_ProductItems)
            {
                sqlList.Add(string.Format("insert into C_ShoppingCart(UserId,ProductId,Product_SkuId,SaleNum)values({0},{1},{2},{3});", _userid, item.ProductId.ToInt(), item.Product_SkuId, item.SaleNum));
            }
            return await sqlService.ExecTransactionAsUpdate_Public(sqlList.ToArray(), null);
        }
    }
}
